/*
 * @Author: your name
 * @Date: 2021-11-29 17:23:11
 * @LastEditTime: 2021-11-29 17:23:11
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \jingfeng_version2\src\assets\js\socket.js
 */
var websock = null
var global_callback = null
var serverPort = '5000' // webSocket连接端口

function getWebIP() {
    var curIP = window.location.hostname
    return curIP
}

function initWebSocket() { // 初始化weosocket
    // ws地址
    var wsuri = 'ws://' + getWebIP() + ':' + serverPort
    websock = new WebSocket(wsuri)
    websock.onmessage = function(e) {
        websocketonmessage(e)
    }
    websock.onclose = function(e) {
        websocketclose(e)
    }
    websock.onopen = function() {
        websocketOpen()
    }

    // 连接发生错误的回调方法
    websock.onerror = function() {
        console.log('WebSocket连接发生错误')
    }
}

// 实际调用的方法
function sendSock(agentData, callback) {
    global_callback = callback
    if (websock.readyState === websock.OPEN) {
        // 若是ws开启状态
        websocketsend(agentData)
    } else {
        // 若未开启 ，则等待1s后重新调用
        setTimeout(function() {
            sendSock(agentData, callback)
        }, 1000)
    }
}

// 数据接收
function websocketonmessage(e) {
    global_callback(JSON.parse(e.data))
}

// 数据发送
function websocketsend(agentData) {
    websock.send(JSON.stringify(agentData))
}

// 关闭
function websocketclose(e) {
    console.log('connection closed (' + e.code + ')')
}

function websocketOpen() {
    console.log('连接成功')
}

initWebSocket()

export {
    sendSock
}
